from django.db import models
from django.utils.translation import ugettext_lazy as _
import re

# Create your models here.

BLOG_POST_RE = re.compile('^[0-9]{4}-[0-9]{2}-[0-9]{2}')

class BlogPostManager(models.Manager):
    def get_query_set(self):
        return super(BlogPostManager, self).get_query_set().filter(latest=True).filter(blog_post=True)


class Article(models.Model):
    name = models.SlugField(_('Page name'))
    body = models.TextField(_('Body'), default=_('Please add some content here'))
    pub_date = models.DateTimeField(_('Updated on'), auto_now_add=True, db_index=True)
    latest = models.BooleanField(_('Latest'), db_index=True)
    blog_post = models.BooleanField(_('Blog post'), db_index=True, default=False)

    objects = models.Manager()
    blog_post_objects = BlogPostManager()

    class Meta:
        verbose_name = _('Article')
        verbose_name_plural = _('Articles')
        get_latest_by = 'pub_date'

    class Admin:
        ordering = ['-latest', 'pub_date']
        list_display = ('name', 'pub_date', 'latest', 'blog_post')
        list_filter = ['latest', 'blog_post']

    def __unicode__(self):
        return self.name

    def save(self, switch_latest=True):
        # TODO: Check if the object has been updated. If it's the same, ignore save.
        if switch_latest:
            self.latest = True
            # There is no such thing as "update"
            self.id = None # With this, you always create a new Article.
        if BLOG_POST_RE.match(self.name):
            self.blog_post = True
        super(Article, self).save()
        if switch_latest:
            for article in Article.objects.filter(name=self.name).exclude(id=self.id):
                article.latest = False
                article.save(switch_latest=False)
